package zj.it.bhne.gridengineeringsurvey.myutils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;

import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.thoughtworks.xstream.core.util.Base64Encoder;

import org.xmlpull.v1.XmlSerializer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;

import zj.it.bhne.gridengineeringsurvey.MyApplication;
import zj.it.bhne.gridengineeringsurvey.R;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Equipment;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Items;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Line;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Photos;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Points;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.EquipmentDao;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.ItemsDao;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.LineDao;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.PhotosDao;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.PointsDao;

import static zj.it.bhne.gridengineeringsurvey.fragment.OneFragment.parseXMLWithPulls;
import static zj.it.bhne.gridengineeringsurvey.myutils.HttpConfig.parseXMLWithPull;
import static zj.it.bhne.gridengineeringsurvey.myutils.ThreadManager.getThreadPool;


/**
 * 导出文件的工具类
 */
public class ExportUnit {


    ProgressDialog mProgressDialog;
    Context context;
    long id;
    String name;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            //若工作完成，取消动画，初始化界面
            mProgressDialog.cancel();
        }
    };
    /**
     * 线程
     */
    private Runnable mRunnable = () -> {
        //需要耗时的工作
        setData();
        Message msg = mHandler.obtainMessage();
        msg.what = 1;
        mHandler.sendMessage(msg);
    };

    /**
     * 为XML文件换行
     */
    private static void changeLine(XmlSerializer serializer, String enter) {
        try {
            serializer.text(enter);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 生成XML文件
     */
    public File getXmlFile(Context context, long id, String name) {
        int REQUEST_EXTERNAL_STORAGE = 1;
        String[] PERMISSIONS_STORAGE = {
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };
        int permission = ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    (Activity) context,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }

        File xmlFile = null;
        List<Items> itemsList = MyApplication.getInstances().getItemsDao().queryBuilder().where(ItemsDao.Properties.Id.eq(id)).build().list();
        Items item = itemsList.get(0);
        List<Points> czzt = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Items_id.eq(id), PointsDao.Properties.Whether.eq("0")).build().list();
        List<Points> czzts = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Items_id.eq(id), PointsDao.Properties.Whether.eq("1")).build().list();
        String enter = System.getProperty("line.separator");//换行
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/bhne/" + name + "/" + name);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }

        try {

            if (czzt.size() > 0) {
                xmlFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/bhne/" + name + "/" + name, name + item.getId() + ".xml");
                xmlFile.setWritable(true);
                FileOutputStream fileos = new FileOutputStream(xmlFile);
                XmlSerializer serializer = Xml.newSerializer();
                serializer.setOutput(fileos, "UTF-8");
                serializer.startDocument(null, true);
                changeLine(serializer, enter);
                serializer.startTag(null, "Projects");
                changeLine(serializer, enter);
                serializer.startTag(null, "ProjectId");
                serializer.text(item.getProjectId() + "");
                serializer.endTag(null, "ProjectId");
                changeLine(serializer, enter);
                serializer.startTag(null, "Voltage");
                serializer.text(item.getVoltage() + "");
                serializer.endTag(null, "Voltage");
                changeLine(serializer, enter);

                for (Points points : czzt) {
                    try {
                        System.getProperty("line.separator");//换行
                        serializer.startTag(null, "Point");
                        serializer.attribute(null, "Dangjv", points.getDangju() + "");
                        serializer.attribute(null, "Weidu", points.getLat() + "");
                        serializer.attribute(null, "Jindu", points.getLon() + "");
                        serializer.attribute(null, "Glsb", points.getGlsb() + "");
                        serializer.attribute(null, "Sbzt", points.getOld() + "");
                        serializer.attribute(null, "Sbbh", points.getMark() + "");
                        serializer.attribute(null, "High", points.getHigh() + "");
                        serializer.attribute(null, "Sblb", points.getName());
                        serializer.attribute(null, "Sblx", points.getSblx());
                        serializer.attribute(null, "Ms", points.getNote() + "");
                        serializer.attribute(null, "ID", points.getEqu_id() + "");
                        serializer.attribute(null, "UID", points.getUid() + "");
                        serializer.attribute(null, "CID", points.getUid() + "");
                        changeLine(serializer, enter);
                    } catch (IOException | IllegalArgumentException | IllegalStateException e) {
                        e.printStackTrace();
                    }

                    List<Equipment> equipmentList = MyApplication.getInstances().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.Point_id.eq(points.getId()), EquipmentDao.Properties.Qubie.eq(2)).build().list();
                    changeLine(serializer, enter);
                    for (Equipment equipment : equipmentList) {
                        serializer.startTag(null, "ColumnModel");
                        serializer.attribute(null, "Amount", equipment.getAmount() + "");
                        serializer.attribute(null, "Module_ID", equipment.getFour_id() + "");
                        serializer.attribute(null, "Module_Name", equipment.getFour_name() + "");
                        serializer.attribute(null, "ModuleXH_ID", equipment.getThree_id() + "");
                        serializer.attribute(null, "ModuleXH_Name", equipment.getThree_name() + "");
                        serializer.attribute(null, "ModuleZL_ID", equipment.getHead_id() + "");
                        serializer.attribute(null, "ModuleZL_Name", equipment.getTwo_name() + "");
                        serializer.attribute(null, "ModuleFL_ID", equipment.getLever_id() + "");
                        serializer.attribute(null, "ModuleFL_Name", equipment.getName() + "");
                        serializer.attribute(null, "Module_Code", equipment.getModule_code() + "");
                        serializer.attribute(null, "PID", points.getUid() + "");
                        serializer.endTag(null, "ColumnModel");
                        changeLine(serializer, enter);
                    }

                    List<Equipment> equipmentList1 = MyApplication.getInstances().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.Point_id.eq(points.getId()), EquipmentDao.Properties.Qubie.eq(0)).build().list();
                    changeLine(serializer, enter);
                    for (Equipment equipment : equipmentList1) {
                        serializer.startTag(null, "PointModel");
                        serializer.attribute(null, "Amount", equipment.getAmount() + "");
                        serializer.attribute(null, "Module_ID", equipment.getFour_id() + "");
                        serializer.attribute(null, "Module_Name", equipment.getFour_name() + "");
                        serializer.attribute(null, "ModuleXH_ID", equipment.getThree_id() + "");
                        serializer.attribute(null, "ModuleXH_Name", equipment.getThree_name() + "");
                        serializer.attribute(null, "ModuleZL_ID", equipment.getHead_id() + "");
                        serializer.attribute(null, "ModuleZL_Name", equipment.getTwo_name() + "");
                        serializer.attribute(null, "ModuleFL_ID", equipment.getLever_id() + "");
                        serializer.attribute(null, "ModuleFL_Name", equipment.getName() + "");
                        serializer.attribute(null, "Module_Code", equipment.getModule_code() + "");
                        serializer.attribute(null, "PID", points.getUid() + "");
                        serializer.endTag(null, "PointModel");
                        changeLine(serializer, enter);
                    }

                    List<Photos> photosList = MyApplication.getInstances().getPhotosDao().queryBuilder().where(PhotosDao.Properties.Points_id.eq(points.getId())).build().list();
                    for (Photos photos : photosList) {
                        serializer.startTag(null, "Multimedia");
                        //serializer.attribute(null, "Multimedia_Name", photos.getName() + "");
                        serializer.attribute(null, "Multimedia_Path", photos.getName() + "");
                        serializer.attribute(null, "PID", points.getUid() + "");
                        serializer.endTag(null, "Multimedia");
                        changeLine(serializer, enter);
                    }
                    serializer.endTag(null, "Point");
                    changeLine(serializer, enter);
                }

                try {
                    if (czzts.size() > 0) {
                        for (Points points : czzts) {
                            serializer.startTag(null, "TopographicPoint");
                            serializer.attribute(null, "uid", points.getUid());
                            serializer.attribute(null, "center_lat", points.getLat());
                            serializer.attribute(null, "center_lng", points.getLon());
                            serializer.attribute(null, "name", points.getName());
                            serializer.attribute(null, "address", points.getAddress());
                            serializer.attribute(null, "t_length", points.getLength());
                            serializer.attribute(null, "t_width", points.getWidth());
                            serializer.attribute(null, "t_hight", points.getHigh());
                            serializer.attribute(null, "t_type", points.getSblx());
                            serializer.attribute(null, "equipId", points.getEqu_id() + "");
                            serializer.attribute(null, "remark", points.getNote());
                            serializer.attribute(null, "t_lat", "");
                            serializer.attribute(null, "t_lng", "");
                            serializer.attribute(null, "rotate_lat", "");
                            serializer.attribute(null, "rotate_lng", "");
                            changeLine(serializer, enter);
                            serializer.endTag(null, "TopographicPoint");
                        }
                    }
                } catch (IOException | IllegalArgumentException | IllegalStateException e) {
                    e.printStackTrace();
                }

                final List<Line> lineList = MyApplication.getInstances().getLineDao().queryBuilder().where(LineDao.Properties.Item_id.eq(id)).build().list();
                if (lineList.size() > 0) {
                    for (Line line : lineList) {
                        serializer.startTag(null, "Line");
                        try {
                            serializer.attribute(null, "Start_equip", line.getStart_id());
                            serializer.attribute(null, "End_equip", line.getEnd_id());
                            serializer.attribute(null, "Line_code", line.getName());
                            serializer.attribute(null, "LineLen", line.getLength());
                            serializer.attribute(null, "LineType", line.getType());
                            serializer.attribute(null, "LineStatue", line.getStatue());
                            serializer.attribute(null, "LineBackNum", line.getBackNum());
                            serializer.attribute(null, "LineNum", line.getNum());
                            serializer.attribute(null, "LineTypeID", line.getType_Id());
                            serializer.attribute(null, "LineLonB", line.getLonB() + "");
                            serializer.attribute(null, "LineLatB", line.getLatB() + "");
                            serializer.attribute(null, "LineLonA", line.getLonA() + "");
                            serializer.attribute(null, "LineLatA", line.getLatA() + "");
                            serializer.attribute(null, "LineName", line.getName());

                            List<Equipment> equipmentList = MyApplication.getInstances().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.Point_id.eq(line.getId()), EquipmentDao.Properties.Qubie.eq(1)).build().list();
                            for (Equipment equipment : equipmentList) {
                                changeLine(serializer, enter);
                                serializer.startTag(null, "LineModel");
                                serializer.attribute(null, "Amount", equipment.getAmount() + "");
                                serializer.attribute(null, "LineXH_ID", equipment.getThree_id() + "");
                                serializer.attribute(null, "LineXH_Name", equipment.getThree_name() + "");
                                serializer.attribute(null, "LineZL_ID", equipment.getHead_id() + "");
                                serializer.attribute(null, "LineZL_Name", equipment.getTwo_name() + "");
                                serializer.attribute(null, "LineFL_ID", equipment.getLever_id() + "");
                                serializer.attribute(null, "LineFL_Name", equipment.getName() + "");
                                serializer.endTag(null, "LineModel");
                            }
                        } catch (IOException | IllegalArgumentException | IllegalStateException e) {
                            e.printStackTrace();
                        }

                        changeLine(serializer, enter);
                        serializer.endTag(null, "Line");
                    }
                }

                try {
                    serializer.endTag(null, "Projects");
                    changeLine(serializer, enter);
                    serializer.endDocument();
                    serializer.flush();
                    fileos.close();
                } catch (IOException | IllegalArgumentException | IllegalStateException e) {
                    e.printStackTrace();
                }

                //MyUtils.getToast(context, "上传成功");

            } else {
                MyUtils.getToast(context, "没有点数据");
                throw new RuntimeException("没有点数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return xmlFile;
    }

    /**
     * 生成Zip文件
     */
    private File getZipFile(Context context, long id, String name) {
        File files = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/bhne/" + name + "/" + name);
        File file = null;
        if (!files.exists() && !files.isDirectory()) {
            files.mkdirs();
        }
        if (getXmlFile(context, id, name) != null) {
            files.setWritable(true);
            try {
                ZipUtils.zip(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name, Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name + ".zip");
            } catch (Exception e) {
                e.printStackTrace();
            }

            file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/bhne/" + name + ".zip");
            file.setWritable(true);
            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //做一些处理
                shareIntent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(context, "zj.it.bhne.gridengineeringsurvey.fileprovider", file));
                shareIntent.setType("text/plain");
                //设置分享列表的标题，并且每次都显示分享列表
                context.startActivity(Intent.createChooser(shareIntent, "分享到"));

            } else {
                //在版本低于此的时候，做一些处理
                shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
                shareIntent.setType("text/plain");
                //设置分享列表的标题，并且每次都显示分享列表
                context.startActivity(Intent.createChooser(shareIntent, "分享到"));
            }
        }

        return file;
    }

    /**
     * 生成Zip文件
     */
    private File getZipsFile(Context context, long id, String name) {
        File files = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/bhne/" + name + "/" + name);
        File file = null;
        if (!files.exists() && !files.isDirectory()) {
            files.mkdirs();
        }
        if (getXmlFile(context, id, name) != null) {
            files.setWritable(true);
            try {
                ZipUtils.zip(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name, Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name + ".zip");
            } catch (Exception e) {
                e.printStackTrace();
            }

            file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/bhne/" + name + ".zip");
            file.setWritable(true);
        }

        return file;
    }

    public void SetExport(final Context context, final long id, final String name) {
        this.context = context;
        this.id = id;
        this.name = name;
        mProgressDialog = new ProgressDialog(context);
        mProgressDialog.setMessage("上传数据中,请稍等...");
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.show();
        //启动线程
        ThreadManager.ThreadPool threadPool = getThreadPool();
        threadPool.execute(mRunnable);

    }

    private void setData() {

        List<Items> itemsList = MyApplication.getInstances().getItemsDao().queryBuilder().where(ItemsDao.Properties.Id.eq(id)).build().list();
        Items items = itemsList.get(0);
        if (MyApplication.getInstances().IsLogin()) {
            if (NetworkUtils.isConnected()) {
                if (items.getState().equals("在线")) {
                    //getToast(context, items.getName() + items.getId() + items.isCheck());
                    LinkedHashMap<String, Object> map = new LinkedHashMap<>();
                    map.put("surverytaskid", items.getProjectId());
                    String result = HttpConfig.callService("getProjectStatusInfo", map);
                    Log.e("TAG", "沛星:     " + items.getProjectId() + "    " + result);
                    if (parseXMLWithPulls(result)) {
                        ToastUtils.showShort("此项目已结束勘测,不可上传");
                    } else {
                        if (GetToken.getInstance().getToken()) {
                            export(context, id, name);
                        } else {
                            GetToken.getInstance().setToken();
                            export(context, id, name);
                        }
                    }
                }
            } else {
                ToastUtils.showShort("网络连接不可用");
            }
        } else {
            ToastUtils.showShort("当前未登录");
        }

    }


    /**
     * 向服务器上传zip包
     */
    private void export(final Context context, final long id, final String name) {
        //TODO 图片来个：如果是xml那么文件名称需要英文要么用时间搓代替。不然乱码后台。调试遇到的问题。
        File files = getZipsFile(context, id, name);


        try {
            if (files != null) {
                LinkedHashMap map = new LinkedHashMap();//TODO 必须用这个有序的 webservers访问需要。有序因为是方法的参数有序的。不然就会调用对应不到。调试遇到的。

                Items items = MyApplication.getInstances().getItemsDao().queryBuilder().where(ItemsDao.Properties.Id.eq(id)).build().list().get(0);

                //TODO 开始-------上传附件
                FileInputStream upfileIn = new FileInputStream(files);
                byte[] upbytes = new byte[upfileIn.available()];
                upfileIn.read(upbytes);
                upfileIn.close();
                //byte[] buffer = bos.toByteArray();
                Base64Encoder encoder = new Base64Encoder();
                String base64str = encoder.encode(upbytes);

                map.put("data", base64str);
                map.put("surverytaskid", items.getProjectId());

                String result = HttpConfig.callService("setSurveyTasksBaseInfo", map);
                Log.e("TAG", "接收手机端传回的勘测多媒体附件信息: " + result);
                if (parseXMLWithPull(result)) {
                    ToastUtils.showShort("上传成功");
                    mProgressDialog.dismiss();
                }else {
                    ToastUtils.showShort("上传失败");
                    mProgressDialog.dismiss();
                }

            } else {
                ToastUtils.showShort("当前项目为空");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //TODO 完成-------

    }

    public void SetLocalExport(final Context context, final long id, final String name) {

        View view = LayoutInflater.from(context).inflate(R.layout.layout_add_concealed_dialog, null);
        Button alertSureTv = view.findViewById(R.id.add_sure);
        Button alertCancelTv = view.findViewById(R.id.add_cancle);
        CheckBox alertCheckBox = view.findViewById(R.id.add_cb);

        //显示确认框
        AlertDialog mAlertDialog = new AlertDialog.Builder(context).setView(view).create();
        mAlertDialog.show();

        //取消
        alertSureTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mAlertDialog.cancel();
            }
        });
        //导出
        alertCancelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (alertCheckBox.isChecked()) {
                    try {
                        getZipFile(context, id, name);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    File file = getXmlFile(context, id, name);
                    try {
                        file.setWritable(true);
                        Intent shareIntent = new Intent();
                        shareIntent.setAction(Intent.ACTION_SEND);

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            //做一些处理
                            shareIntent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(context, "zj.it.bhne.gridengineeringsurvey.fileprovider", file));
                            shareIntent.setType("text/plain");
                            //设置分享列表的标题，并且每次都显示分享列表
                            context.startActivity(Intent.createChooser(shareIntent, "分享到"));

                        } else {
                            //在版本低于此的时候，做一些处理
                            shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
                            shareIntent.setType("text/plain");
                            //设置分享列表的标题，并且每次都显示分享列表
                            context.startActivity(Intent.createChooser(shareIntent, "分享到"));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        MyUtils.getToast(context, "没有点数据");
                    }
                }
                mAlertDialog.cancel();
            }
        });

    }

}
